#include "JsonParser.h"

using namespace BOOST_SPIRIT_CLASSIC_NS;


bool	parse_list(char const* str, list<string>& list)
{
  rule<>	list_end_rule = ']' >> !(ch_p(','));
  rule<>	node_end_rule = '}' >> !(ch_p(','));
  rule<>	node_rule = confix_p('{', *(node_rule | anychar_p), node_end_rule);
  rule<>	list_rule = '[' >>		\
    *(node_rule[push_back_a(list)]) >>		\
    list_end_rule;

  return parse(str, list_rule, ch_p('\n')).full;
}

list<string>		JsonParser::extract_list(const string& str)
{
  list<string>		list;

  parse_list(str.c_str(), list);
  return list;
}

bool	parse_node(char const* str, map<string, string>& map)
{
  string	result;
  rule<>	string_rule = *((ch_p('\\') >> anychar_p) | ~(ch_p('"')));
  rule<>	node_end_rule = '}' >> !(ch_p(','));
  rule<>	node_ignore = confix_p('{', *(node_ignore | anychar_p), node_end_rule);
  rule<>	list_end_rule = ']' >> !(ch_p(','));
  rule<>	list_ignore = confix_p('[', *(list_ignore | anychar_p), list_end_rule);
  rule<>	alnum_rule = *(alnum_p);
  rule<>	node_rule = '{'	>>					\
    *('"' >> string_rule[assign(result)] >> '"' >> ':' >>		\
      ((node_ignore[insert_at_a(map, result)]) |			\
       (list_ignore[insert_at_a(map, result)]) |			\
       ('"' >> string_rule[insert_at_a(map, result)] >> '"' >> !(ch_p(','))) | \
       (alnum_rule[insert_at_a(map, result)] >> !(ch_p(','))))) >>	\
    node_end_rule;
    
  return parse(str, node_rule, ch_p('\n')).full;
}

map<string, string>	JsonParser::extract_map(const string& str)
{
  map<string, string>	map;
  
  parse_node(str.c_str(), map);
  return map;
}
